package com.xyh.concurrency.example.lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.StampedLock;

import lombok.extern.slf4j.Slf4j;

/**
 * juc 中的锁
 * StampedLock 锁的基本是用效率很好
 */
@Slf4j
public class LockExample4 {
    //创建初始化新线程
    private static int clientTotal = 5000;
    //允许并发的线程数
    private static int threadTotal = 200;
    private static int count = 50;
    private static StampedLock stampedLock = new StampedLock();

    public static void main(String[] args) throws InterruptedException {
        //创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //创建并发允许额数量
        final Semaphore semaphore = new Semaphore(threadTotal);
        //最大线程数
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    //开启线程阻塞
                    semaphore.acquire();
                    add();
                    //关闭线程阻塞,释放后钱200 线程
                    semaphore.release();
                } catch (Exception ex) {
                    log.error("name", ex.toString());
                }
                countDownLatch.countDown();
            });

        }

        countDownLatch.await();
        executorService.shutdown();
        log.info("cpunt:{}", count);

    }

    public static void add() {
        //写的时候进行线程独享,读的时候进行乐观锁的切换,但是当出现有线程正在写就不呢能进行线程的释放
        long l = stampedLock.writeLock();
        try {
            count++;
        } finally {
            stampedLock.unlock(l);
        }


    }
}
